//
//  MenuListContent.m
//  AppleCilent
//
//  Created by Nail Sharipov on 08/04/14.
//  Copyright (c) 2014 Nail Sharipov. All rights reserved.
//

#import "MenuListContent.h"
#import "MainProperties.h"
#import "MenuButton.h"
#import "ResourceData.h"
#import "SceneManager.h"
#import "GoodsListViewController.h"

@implementation MenuListContent

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        NSArray* menuList = [[ResourceData getInstance] menuList];
        
        int n = (int)[menuList count];
        
        UIScrollView* scrollView = self;
        
        CGRect rect = [scrollView frame];
        
        int columnCount = 3;
        float borderMargin = 16.0f;
        float textHeight = 16.0f;
        float contentMargin = 32.0f;
        
        float buttonWidth = (rect.size.width - 2*borderMargin - (columnCount - 1)*contentMargin ) / columnCount;
        float buttonHeight = buttonWidth + textHeight;
        
        int level = (n - 1)/3 + 1;
        
        float height = level * (buttonHeight + contentMargin) + borderMargin;
        
        [scrollView setContentSize: CGSizeMake(rect.size.width, height)];
        
        int i = 0;
        
        NSString* imageFolderPath = [[MainProperties getInstance] getImageFolder];
        
        for (MenuDomain* menu in menuList) {
            int x = (i % 3)*(buttonWidth + contentMargin) + borderMargin;
            int y = (i / 3)*(buttonHeight + contentMargin) + borderMargin;
            
            NSString* imageName = [menu getImage];
            NSString* imagePath = [NSString stringWithFormat:@"%@/%@", imageFolderPath, imageName];
            
            UIImage* image = [UIImage imageWithContentsOfFile:imagePath];
            
            MenuButton* button = [[MenuButton alloc] initWithFrame:CGRectMake(x, y, buttonWidth, buttonHeight)];
            [button setImage:image];
            [button setText:[menu getName]];
            [button addClickHandlerEvent:[menu getId] onClick:^(NSInteger itemId)
             {
                 [self onMenuClick:itemId];
             }];
            
            [scrollView addSubview:button];
            
            i++;
        }
    }
    return self;
}

- (void)onMenuClick: (NSInteger)menuId
{
    GoodsListViewController* viewController = (GoodsListViewController*)[[SceneManager getInstance] openScene: @"GoodsList"];
    MenuDomain* menu = [[ResourceData getInstance] getMenuById:menuId];
    [viewController setMenu:menu];
    
}

@end
